import { ref, reactive } from 'vue'
import { logOut, updatePassword } from '~/api/manager'
import { showModal, toast } from '~/composables/util'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export function userRepassWord() {
  const store = useStore()
  const router = useRouter()
  // 修改密码部分
  const formDrawerRef = ref(null)
  // do not use same name with ref
  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: ''
  })

  // 定义form表单的校验规则
  const rules = {
    oldpassword: [
      {
        required: true,
        message: '旧密码不能为空',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        message: '新密码不能为空',
        trigger: 'blur'
      }
    ],
    repassword: [
      {
        required: true,
        message: '确认密码不能为空',
        trigger: 'blur'
      }
    ]
  }

  const formRef = ref(null)
  const onSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      // 在调用接口前按钮有loading状态
      formDrawerRef.value.showLoading()
      updatePassword(form)
        .then((res) => {
          // 提示修改密码成功
          toast('修改密码成功,请重新登录')
          // 退出登录
          store.dispatch('logout')
          // 跳转回登录页面
          router.push('/login')
        })
        .finally(() => {
          // 在调用接口完毕后按钮关闭loading状态
          formDrawerRef.value.hideLoading()
        })
    })
  }

  const openRePasswordForm = () => formDrawerRef.value.open()

  return {
    formDrawerRef,
    form,
    rules,
    formRef,
    onSubmit,
    openRePasswordForm
  }
}

export function useLogout() {
  const store = useStore()
  const router = useRouter()
  function logout() {
    showModal('是否要退出登录?').then((res) => {
      logOut().finally(() => {
        store.dispatch('logout')
        // 跳转回登录页面
        router.push('/login')
        // 提示退出登录成功
        toast('退出登录成功')
      })
    })
  }
  return { logout }
}